<!--
 * @name order
 * @description 组件描述
 * @author idouya
 * @email elegentfrog@163.com
 * @date 2025-07-02
 -->

<template>
  <div class="p-score common-bg common-layout">
    <page-title
      :discipline="gameInfo.discipline"
      :event="gameInfo.event"
      :match="gameInfo.match"
      :type="gameInfo.type"
    ></page-title>
    <div class="content">
      <div class="top">
        <div class="top-left">
          <div class="order common">{{ scoreInfo.Order }}</div>
          <div class="delegation common">{{ scoreInfo.CountryName }}</div>
        </div>
        <div class="top-center">
          <div class="name center-common">{{ scoreInfo.AthleteName }}</div>
          <div class="horseName center-common">{{ scoreInfo.HorseName }}</div>
        </div>
        <div class="top-right">
          <div class="allow-time" v-show="scoreInfo.AllowTime">
            允许时间：{{ scoreInfo.AllowTime }}秒
          </div>
        </div>
      </div>
      <div class="bottom">
        <div class="bottom-left">
          {{ level == 0 ? runTimeResult : runTime }}
        </div>
        <div class="bottom-right">
          <div class="left">
            <div class="text1">得分</div>
            <div class="text2">马术</div>
            <div class="score">{{ getTotalScore }}</div>
          </div>
          <div class="right">
            <div class="right-top">--- 罚分 ---</div>
            <div class="right-center">
              <div class="text">障碍</div>
              <div class="text">时间</div>
            </div>
            <div class="right-bottom">
              <div class="text">{{ scoreInfo.ObstaclePunish }}</div>
              <div class="text">
                {{ getTimePunish % 1 !== 0 ? getTimePunish.toFixed(0) : getTimePunish }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import useStore from '@/store'
import Storage from '@/assets/js/storage'
import Utils from '@/assets/js/utils'
import Config from '@/assets/js/config'
import PageTitle from '@/components/scb/PageTitle.vue'
import { useMultiProcRequest } from '@/assets/js/useMultiProcRequest'
import { computed } from 'vue'

const { results, fetchForProcs, formatToFixed2 } = useMultiProcRequest()

const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
const params = ref({})
const procName = ref([])

const runTime = ref(45)
const isRunning1 = ref(false)
const isRunning2 = ref(false)
const commonStore = useStore.useCommonStore()

const gameInfo = ref({
  discipline: '现代五项',
  match: '马术',
  event: 'PENTATHLON',
  type: '实时成绩',
})

const scoreInfo = ref({
  order: 1,
  rank: 1,
  name: '杨舒涵',
  horseOrder: 45,
  horseName: 'Joanna',
  delegation: '湖北',
  allowTime: '76',
  equestrian: '300',
  obstacle: '53',
  time: '12',
  ObstaclePunish: 0,
  TimePunish: 0,
})

let timer1 = null
let timer2 = null

const isRunning = ref(false)
const TIMEOUT_MS = 45000
const runTimeResult = ref(45)
const level = ref(null)
const baseRunTime = ref(0)
const hasStartedOnce = ref(false)
let pastRunTimeMs = 0 // 之前已经运行了多少毫秒
let startTimeMs = 0 // 本轮开始时间戳（毫秒）
const TotalScore = ref(300)

const PunishTimeNum = ref(1)
const PunishTimeUnit = ref(1)

const scoreObj = ref({
  ObstaclePunish: 0,
  TimePunish: 0,
})
const time0 = ref(0)
const time1 = ref(0)

onUnmounted(() => {
  clearInterval(timer1)
  clearInterval(timer2)
})

onBeforeMount(() => {
  clearInterval(timer1)
  clearInterval(timer2)
})

onMounted(async () => {
  params.value = route.query
  procName.value = Config.procNameList[route.name]
  await getData()
  const lastMsg = commonStore.receivedActionMessages?.slice(-1)[0]
  if (lastMsg && lastMsg.tplCode == 'scb-pentathlon-score') {
    init(lastMsg)
  }
  startTimer1()
  startTimer2()
})

const getTimePunish = computed(() => {
  if (!isRunning2.value || !scoreInfo.value) return scoreInfo.value?.TimePunish || 0

  const runTimeValue = parseFloat(runTime.value) || 0
  const allowTime = scoreInfo.value.AllowTime || 0

  if (runTimeValue >= allowTime) {
    const timeDiff = runTimeValue - allowTime
    return Math.floor(timeDiff / PunishTimeNum.value) * PunishTimeUnit.value
  }
  return scoreInfo.value.TimePunish || 0
})

const getTotalScore = computed(() => {
  const timePunish = Number(getTimePunish.value) || 0
  const obstaclePunish = Number(scoreInfo.value?.ObstaclePunish) || 0
  const totalScore = Number(TotalScore.value) || 0

  return totalScore - timePunish - obstaclePunish
})

const getData = async () => {
  if (procName.value.length > 0) {
    await fetchForProcs(procName.value, {
      procName: procName.value[0],
      keyValues: params.value,
    })
  }
}

const startTimer1 = () => {
  timer1 = setInterval(() => {
    if (isRunning1.value && runTimeResult.value > 0) {
      const now = new Date().getTime()
      const totalElapsed = pastRunTimeMs + (now - startTimeMs)
      const remainingMs = TIMEOUT_MS - totalElapsed
      runTimeResult.value = (remainingMs / 1000).toFixed(0)
    }
  }, 200)
}

const startTimer2 = () => {
  timer2 = setInterval(() => {
    if (isRunning2.value) {
      time1.value = new Date().getTime()
      runTime.value = (baseRunTime.value + (time1.value - time0.value) / 1000).toFixed(1)
    }
  }, 20)
}

const floorToFixed = (num, decimals = 2) => {
  if (!num) return 0 // ⚠️ num=0 时直接返回 null
  const numStr = num.toString()
  const decimalIndex = numStr.indexOf('.')

  if (decimalIndex === -1) {
    return num.toFixed(decimals) // 整数直接补零
  }

  // 直接截取所需小数位
  const truncatedStr = numStr.substring(0, decimalIndex + decimals + 1)
  return parseFloat(truncatedStr).toFixed(decimals)
}

const handleMessage1 = (msg) => {
  const data = msg?.data
  if (!data) return
  scoreInfo.value.ObstaclePunish = data.penPoint
  scoreInfo.value.TimePunish = Math.floor(data.penTime / PunishTimeNum.value) * PunishTimeUnit.value
  if (data.status == 1) {
    startTimeMs = new Date().getTime()
    pastRunTimeMs = data.runTime // 假设单位是秒
    isRunning1.value = true
  } else {
    // runTimeResult.value = 45
    isRunning1.value = false
    // runTime.value = data.runTime
    pastRunTimeMs = data.runTime
    runTimeResult.value = (45 - data.runTime / 1000).toFixed(0)
    if (data.status == 3 && data.runTime == 45000) {
      runTime.value = 0
    } else {
      runTime.value = floorToFixed(0.001 * data.runTime, 1)
    }
  }
}

const handleMessage2 = (msg) => {
  const data = msg?.data
  if (!data) return
  if (data?.status == 1) {
    baseRunTime.value = data?.runTime
    if (!hasStartedOnce.value) {
      time0.value = new Date().getTime()
      hasStartedOnce.value = true
    } else {
      // 继续运行：修正 time0，避免 runTime 增加错位
      time0.value = new Date().getTime()
    }
    isRunning2.value = true
    scoreInfo.value.ObstaclePunish = data.penPoint
    scoreInfo.value.TimePunish =
      Math.floor(data.penTime / PunishTimeNum.value) * PunishTimeUnit.value
    scoreInfo.value.RoundPunish =
      Math.floor(data.penTime / PunishTimeNum.value) * PunishTimeUnit.value + data.penPoint
    scoreInfo.value.RedressTime = data.redressTime || 0
  } else if (data?.status == 0 || data?.status == 2) {
    isRunning2.value = false
    baseRunTime.value = runTime.value
    scoreInfo.value.ObstaclePunish = data.penPoint
    scoreInfo.value.TimePunish =
      Math.floor(data.penTime / PunishTimeNum.value) * PunishTimeUnit.value
    scoreInfo.value.RoundPunish =
      Math.floor(data.penTime / PunishTimeNum.value) * PunishTimeUnit.value + data.penPoint
    scoreInfo.value.RedressTime = data.redressTime || 0
    runTime.value = data.runTime > 0 ? floorToFixed(data.runTime, 2) : 0
  } else if (data?.status == 3) {
    isRunning2.value = false
    hasStartedOnce.value = false
    baseRunTime.value = 0
    runTime.value = data.runTime > 0 ? floorToFixed(data.runTime, 2) : 0
    scoreInfo.value.ObstaclePunish = data.penPoint
    scoreInfo.value.TimePunish =
      Math.floor(data.penTime / PunishTimeNum.value) * PunishTimeUnit.value
    scoreInfo.value.RoundPunish =
      Math.floor(data.penTime / PunishTimeNum.value) * PunishTimeUnit.value + data.penPoint

    scoreInfo.value.RedressTime = data.redressTime || 0
    if (data.postFlag == 1) {
      getData()
    }
  }
}

const handleMessage3 = (msg) => {
  const data = msg?.data
  runTime.value = data.irm
}

const init = (latestMsg) => {
  const data = latestMsg?.data
  level.value = data?.level
  if (data?.level == 0) {
    isRunning2.value = false
    handleMessage1(latestMsg)
  } else if (data?.level == 1) {
    isRunning1.value = false
    // runTime.value = 0
    handleMessage2(latestMsg)
  } else if (data?.level == 2) {
    isRunning1.value = false
    isRunning2.value = false
    handleMessage3(latestMsg)
  }
}

watchEffect(() => {
  if (results.value?.recordset?.length) {
    const data = results.value.recordset[0]
    scoreInfo.value = {
      ...scoreInfo.value,
      Order: data?.Order,
      AthleteName: data?.AthleteName,
      CountryName: data?.CountryName,
      HorseName: data?.HorseName,
      HorseOrder: data?.HorseOrder,
      AllowTime: data?.AllowTime,
    }
    PunishTimeNum.value = data?.m || 1
    PunishTimeUnit.value = data?.n || 1
  }
})

watch(
  () => commonStore.receivedActionMessages,
  (newVal, oldVal) => {
    if (newVal.length > 0) {
      const latestMsg = newVal[newVal.length - 1]
      init(latestMsg)
    }
  },
  { deep: true }
)

watch(
  () => route.query,
  (val) => {
    params.value = val
    getData()
  }
)
</script>

<style scoped lang="scss">
@import '@/assets/scss/pentathlon/score';

.top-left {
  display: flex;
  flex-direction: column;
}
</style>
